package crm.controller;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.metal.MetalTextFieldUI;
import javax.swing.table.DefaultTableModel;

import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

import crm.daoInterfaces.ActionNameDao;
import crm.daoInterfaces.FollowUpActionDao;
import crm.daoInterfaces.InquiryStateDao;
import crm.daoInterfaces.LeadsDao;
import crm.daoInterfaces.PriorityDao;
import crm.daoInterfaces.ProductDao;
import crm.daoInterfaces.SalesPersonDao;
import crm.dto.ActionName;
import crm.dto.InquiryState;
import crm.dto.Leads;
import crm.dto.Priority;
import crm.dto.Product;
import crm.dto.SalesPerson;
import crm.implementor.ActionNameImp;
import crm.implementor.FollowUpActionImp;
import crm.implementor.InquiryStateImp;
import crm.implementor.LeadsImp;
import crm.implementor.PriorityImp;
import crm.implementor.ProductImp;
import crm.implementor.SalesPersonImp;
import crm.model.FollowUpAction;
import crm.utility.AppUtility;
import crm.utility.ViewUtilites;
import crm.view.leeds.FollowupActionsView;
import crm.viewframework.Validater;





@SuppressWarnings("unused")
public class FollowUpActionsController implements ActionListener, ItemListener
{
	private FollowupActionsView view;
	private Leads model;
	private Vector<NameNumber>pair;
	
	
	
	public FollowUpActionsController() 
	{
		
	}

	
	

	public FollowUpActionsController(FollowupActionsView view, Leads model) {
		super();
		this.view = view;
		this.model = model;
		view.actionListener(this);
		pair=new Vector<NameNumber>();
		try {
			
			AppUtility.setComboAtten(view.getComboAttended());
			AppUtility.setComboPriority(view.getComboLeadPriority());
			AppUtility.setComboStatus(view.getComboStatus());
			this.setComboNewFollow(view.gettNewFollowup());
			
			// IF MODEL IS NOT NULL IT MEANS MODEL IS FILLED FROM DATABASE SO APPROPRIATE VIEWS NEEDS TO BE FILLED
			if(model!=null)
			{
				setTable();
				setViews();
				
				
			}
			else
			{
				
				
				
				setLeadSuggestions();
				view.getTfLeadName().addItemListener(this);
				
				
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}



	

	public FollowupActionsView getView() {
		return view;
	}




	public void setView(FollowupActionsView view) {
		this.view = view;
	}




	public Leads getModel() {
		return model;
	}




	public void setModel(Leads model) {
		this.model = model;
	}

	public void setComboNewFollow(@SuppressWarnings("rawtypes") JComboBox comboBox) throws Exception
	{
		ActionNameDao a=new ActionNameImp();
		ActionName[] action=a.retrieveAll();
		String[] actionNames=new String[action.length+1];
		actionNames[0]="--Select Product--";
		for(int i=1;i<=action.length;i++)
		{
			actionNames[i]=action[i-1].getActionName();
		}
		ViewUtilites.set_comboBox(view.gettNewFollowup(),actionNames);
	}
	
	
	public void setTable()
	{
		
		FollowUpAction[] myFollow=model.getModelfoll();
		
		DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
		for(int i=0;i<myFollow.length;i++)
		{
			dm.addRow(new Object[]{myFollow[i].getActionName(),myFollow[i].getAttendedId(),myFollow[i].getFollowUpDate(),myFollow[i].getComments()});
		}
	}
	
	
	

	
	public void reactToAdd() throws Exception
	{
	    //Get the data from view
		String NewAction=view.gettNewFollowup().getSelectedItem().toString();
		String result=view.getTextAreaResult().getText();
		String attendedBy= view.getComboAttended().getSelectedItem().toString();
		java.sql.Date dates=ViewUtilites.convert(view.getLblClick().getText());
		Timestamp t=ViewUtilites.getTime();
		
		// Get the id
		int id=AppUtility.getSalesPersonId(attendedBy);
		int stateId=AppUtility.getImquiryStateId(model.getModelstateName());
		
		try
		{
			FollowUpAction follow=new FollowUpAction(model.getAutoenquiryCode(), stateId, id, result, dates, t,1);
			FollowUpActionImp followupact=new FollowUpActionImp();
			followupact.add(follow);
			
			// Add in Table
			JOptionPane.showMessageDialog(null, "Data successfully added");
			DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
			dm.addRow(new Object[]{follow.getActionName(),attendedBy,follow.getFollowUpDate()+"",follow.getComments()});
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
		
		}	
	}
	
	public void updateStatus() throws Exception
	{
		
		
		
		String p=view.getComboStatus().getSelectedItem().toString();
		int stateId=AppUtility.getImquiryStateId(p);
		model.setStateId(stateId);
		LeadsDao lead= new LeadsImp();
		lead.update(model);
	}
	
	public void updatePriority() throws Exception
	{
		String p=view.getComboLeadPriority().getSelectedItem().toString();
		model.setPriorityName(p);
		LeadsDao leads = new LeadsImp();
		leads.update(model);
			
		
	
		
	}
	
	@SuppressWarnings("unchecked")
	private void setLeadSuggestions() throws SQLException
	{
		
		ArrayList<String>array = new ArrayList<String>();
		try {
			new LeadsImp();
			Leads[]leads=LeadsImp.getLeadsByFilter(null,null,"all","all");
		    
			int i=0;
			
			view.getTfLeadName().addItem("---Select Name---");
			for(Leads l:leads)
			{
				view.getTfLeadName().addItem(l.getModelname());
				i++;
				
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		AutoCompleteDecorator.decorate(view.getTfLeadName());
	}
	
	@SuppressWarnings("unchecked")
	private void setViews()
	{
		view.getTfLeadName().addItem(model.getModelname());
		view.getTfLeadName().setEditable(false);
		view.getLblleadNo().setText(model.getAutoenquiryCode()+"");
		view.getLblregDate().setText(model.getEnquiryDate()+"");
		view.getTfLeadPriority().setText(model.getPriorityName());
		view.getTfleadStatus().setText(model.getModelstateName());
		//view.getTfLeadPriority().setText(model.getPriorityName());
	}

	
	
	
	@Override
	public void actionPerformed(ActionEvent arg0) 
	{
		String k=arg0.getActionCommand();
		if(k.contains("changePriority"))
		{
			try {
				updatePriority();
				JOptionPane.showMessageDialog(null,"PRIORITY UPDATED!");
			} 
			catch (Exception e) {
				
				JOptionPane.showMessageDialog(null,"FAILED TO UPDATE !");
				e.printStackTrace();
			}
		}
		if(k.contains("changeStatus"))
		{
			try {
				updateStatus();
				JOptionPane.showMessageDialog(null,"STATUS UPDATED!");
			} 
			catch (Exception e) {
				JOptionPane.showMessageDialog(null,"FAILED TO SAVE !");
				e.printStackTrace();
			}
		}
		if(k.contains("Add"))
		{
			try {
				reactToAdd();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		if(k.contains("Send Email"))
		{
			
		}
		if(k.contains("Send SMS"))
		{
			
		}
		if(k.contains("Cl"))
		{
			ViewUtilites.makeDateComponent(view.getLblClick());
		}
		
	}




	




	@Override
	public void itemStateChanged(ItemEvent arg0) {
		if(arg0.getStateChange() == ItemEvent.SELECTED)
		{
			Validater val = new Validater(view);
			int index =view.getTfLeadName().getSelectedIndex();
			if(index == 0)
				val.refresh();
			else
			{
				index =view.getTfLeadName().getSelectedIndex();
				LeadsDao dao = new LeadsImp();
				try {
					model = dao.retrieve("autoenquiryCode",this.pair.get(index).number+"");
					setViews();
					
					
					
					
				} catch (Exception e) {
					
					e.printStackTrace();
				}
				
			}
		}
		
	}
	




//***************************************************Inner Class******************************************************//
	
private class NameNumber
{
	private String name;
	private int number;
}

}
